<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="phone">
      <el-input
        class="inputDeep"
        v-model="loginForm.phone"
        oninput="value=value.replace(/[^\d]/g,'')"
        autocomplete="off"
        placeholder="请输入手机号"
      >
        <template #prefix>
          <el-icon><Phone /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="verificationCode" v-if="env.VITE_RELEASE_NAME === 'fendi'">
      <div class="flx-default w100">
        <el-input class="inputDeep" v-model="loginForm.verificationCode" placeholder="验证码">
          <template #prefix>
            <i class="iconfont icon-yanzhengma" />
          </template>
        </el-input>
        <img class="yzm" @click="getDynamicCode()" :src="dynamicCode" />
      </div>
    </el-form-item>
    <el-form-item prop="code">
      <el-input class="inputDeep" v-model="loginForm.code" placeholder="请输入验证码">
        <template #prefix>
          <span class="input-prefix-text">手机验证码</span>
        </template>
        <template #suffix>
          <div @click.stop>
            <el-button @click="getCaptcha" :disabled="codeText === '获取验证码' ? false : true" text class="input-suffix-text">{{
              codeText
            }}</el-button>
          </div>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button size="large" type="primary" :loading="loading" @click="login(loginFormRef)" color="#ff6200" style="color: #ffffff">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, unref } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi, sendVeriCode, getIdentify } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
// import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
// import md5 from "js-md5";

const env = ref(import.meta.env);
const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const codeText = ref("获取验证码");

type FormInstance = InstanceType<typeof ElForm>;
// 手机号码自定义验证规则
const telValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入手机号"));
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  phone: [{ required: true, validator: telValidator, trigger: "blur" }],
  verificationCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  code: [{ required: true, message: "请输入手机验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginFormCode>({
  phone: "",
  code: "",
  verificationCode: "",
  verificationKey: "",
  clientType: 1
});

const dynamicCode = ref("");
const getDynamicCode = async () => {
  if (env.value.VITE_RELEASE_NAME !== "fendi") return;
  const { data } = await getIdentify();
  dynamicCode.value = data.verificationCode;
  loginForm.verificationKey = data.verificationKey;
};

const getCaptcha = async () => {
  const formRef: any = unref(loginFormRef);
  formRef.validateField(["phone", "verificationCode"], (valid: boolean) => {
    if (valid) {
      let n = 60;
      sendVeriCode({
        mobile: loginForm.phone,
        verificationCode: loginForm.verificationCode,
        verificationKey: loginForm.verificationKey
      })
        .then(() => {
          codeText.value = n + "秒钟重新获取";
          const timer = setInterval(() => {
            if (n === 0) {
              clearInterval(timer);
              codeText.value = "获取验证码";
            } else {
              n--;
              codeText.value = n + "秒钟重新获取";
            }
          }, 1000);
        })
        .catch(() => {
          getDynamicCode();
        });
    }
  });
};

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      // const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
      const { data } = await loginApi(loginForm);
      userStore.setToken(`${data.token.token_type} ${data.token.token}`);
      userStore.setUserInfo(data.sysUser);
      userStore.setStore(data.store);
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录!",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

onMounted(() => {
  getDynamicCode();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../login.scss";
</style>
